<template>
  <div class="app-page">
    <div>
      <div style="margin: 10px 0;">
        <el-button style=" display: inline-block; width: 150px;" :type="type === 'three' ? 'primary' : 'default'" @click="queryTime('three')">近三天</el-button>
        <el-button style="display: inline-block; width: 150px;" :type="type === 'week' ? 'primary' : 'default'" @click="queryTime('week')">近七天</el-button>
        <el-button style="display: inline-block; width: 150px;" :type="type === 'month' ? 'primary' : 'default'" @click="queryTime('month')">近一个月</el-button>
      </div>
      <el-table-form ref="form" :model="query">
        <el-form-item label="订单下单时间:" :table-form-merge="2">
          <el-date-picker
            v-model="query.date"
            type="datetimerange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="true"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="派单状态:" class="merge-item">
          <el-select v-model="query.orderDispatchStaus" placeholder="请选择" clearable>
            <el-option
              v-for="item in orderDispatchStausMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
          <div style="width: 120px; padding-left: 20px;">
            <el-checkbox v-model="query.tranStatus" :true-label="1">未派单</el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="所属机构:" class="merge-item" :table-form-merge="1.5">
          <el-tree-select
            v-model="query.orgSNNo"
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              loading: $loadingPlugin.getTreeData
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
            @node-click="selectTreeChange"
            @select-clear="closeTree"
          />
          <div style="width: 120px; padding-left: 20px;">
            <el-checkbox v-model="query.option" label="包含下级" />
          </div>
        </el-form-item>
        <el-form-item style="margin-left: 5px;" label="" class="merge-item" :table-form-merge="1">
          <template slot="label">
            归属人:
          </template>
          <el-select v-model="query.userId" multiple collapse-tags :loading="$loadingPlugin.getOwnersList" style="width: 100%;" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in ownersList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间:" :table-form-merge="2">
          <el-date-picker
            v-model="query.date1"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="true"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-form-item>

        <!-- <el-form-item label="在线配送员:">
          <el-tree-select
            v-model="userNameOnline"
            clearable
            class="tree-select"
            :default-label="defaultLabel"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              multiple: true
            }"
            :value="userNameOnline"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props:{
                value:'userId',
                label: 'userName',
                disabled: 'disabled',
              },
              data: orgidData.data
            }"
            @select-clear="closeTree"
            @check="selectCheck"
            @input="inputChange"
          />
        </el-form-item> -->
        <template v-slot:btns>
          <!-- <span v-if="showSwitch">自动转派:</span>
          <el-switch
            v-if="showSwitch"
            v-model="dispatchFlag"
            class="switch-item"
            active-color="#01999F"
            inactive-color="#909399"
            @change="dispatchFlagChange"
          /> -->
          <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>
    </div>
    <div class="handle-row">
      <div class="statistics">
        <div v-if="tactics" class="tactics" style="margin-bottom: 5px;">
          <div>自动派单：<span :style="{color:tactics.isOpen===1?'#13ce66':' #ff4949'}">{{ tactics.isOpen===1?'已开启':'已关闭' }}</span></div>
          <template v-if="tactics.isOpen===1">
            <div style="color: #409EFF; cursor: pointer;" @click="openTacticsDetail(tactics)">{{ tactics.strategyName }}</div>
            <div style="color: #F56C6C;">{{ tactics.dispatchTime }}</div>
          </template>

        </div>
        <div v-if="statistics" class="btnInfo" style="margin-bottom: 5px;">
          <div>已派单：
            <el-tooltip placement="bottom">
              <div slot="content">已派单：所属机构今日所有途径派单成功的订单总和<br>
                未派单：查询条件所选日期所属机构没有派单的订单<br>
                派单成功（自动）：所属机构今日已自动派单成功的订单<br>
                派单失败（自动）：所属机构今日已自动派单失败的订单<br>
                调度员：查询条件所选日期所属机构调度员手中的订单</div>
              <i class="el-icon-question" />
            </el-tooltip>
            <el-tooltip placement="bottom">
              <div slot="content">已派单：{{ statistics.dispatched }}单<br>
                自动派单：{{ statistics.autoDispatch }}单<br>
                手动派单：{{ statistics.operateDispatch }}单<br>
                呼叫中心派单：{{ statistics.callCenterDispatch }}单<br>
                话务派单：{{ statistics.phoneDispatch }}单<br>
                门店派单：{{ statistics.storeDispatch }}单<br>
                代客派单：{{ statistics.valetDispatch }}单
              </div>
              <el-link style="color: #409EFF;" :underline="false">{{ statistics.dispatched }}</el-link>
            </el-tooltip>
          </div>
          <div>未派单：{{ statistics.noDispatch }}</div>
          <div>派单成功（自动）：{{ statistics.autoDispatchSuccess }}</div>
          <div>派单失败（自动）：{{ statistics.autoDispatchFail }}</div>
          <div>调度员：{{ statistics.orderOfDispatcher }}</div>
        </div>
        <div class="btnInfo" style="margin-bottom: 10px;">
          <img v-if="swich==='map'" src="@/assets/map_images/red_sprite.png">
          <span v-if="swich==='map'">未派单({{ orderOne }})</span>
          <img v-if="swich==='map'" src="@/assets/map_images/blue_sprite.png">
          <span v-if="swich==='map'">已选中({{ orderTwo }})</span>
          <img v-if="swich==='map'" src="@/assets/map_images/yellow_sprite.png">
          <span v-if="swich==='map'">调度员({{ orderThree }})</span>
          <img v-if="swich==='map'" src="@/assets/map_images/green_sprite.png">
          <span v-if="swich==='map'">待接单({{ orderFour }})</span>
        </div>
      </div>
      <div>
        <div style="display: inline-block; width: 150px; padding-left: 20px;">
          <el-checkbox v-model="automaticPrint" @change="chooseAutomaticPrint">分派自动打印</el-checkbox>
        </div>
        <div style="display: inline-block; padding-right: 20px;">
          <div class="el-form-item__label" style="display: inline-block;">在线配送员:</div>
          <el-tree-select
            v-model="userNameOnline"
            clearable
            class="tree-select"
            style="display: inline-block;"
            :default-label="defaultLabel"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              multiple: true
            }"
            :value="userNameOnline"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props:{
                value:'userId',
                label: 'userName',
                disabled: 'disabled',
              },
              data: orgidData.data
            }"
            @select-clear="closeTag"
            @check="selectCheck"
            @input="inputChange"
          />
        </div>
        <el-link v-permission="2" :underline="false" style=" display: inline-block; font-size: 16px; color: #126edc;" class="btn" size="mini" @click="cut"> <i style="transform: rotate(-90deg);" class="el-icon-sort" />&nbsp;{{ swich==="form"?'地图模式':'表格模式' }}</el-link>
      </div>

    </div>
    <div class="table_Main">
      <lb-table
        v-show="swich==='form'"
        ref="lbTable"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        class="left"
        highlight-current-row
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        :immediate-fetch="false"
        @selection-change="handleSelectionChange"
        @fetch="fetchData"
      />
      <div class="total">本次选择 单数：{{ muList.length }} 商品数：{{ goodsTotal }}</div>
      <div v-if="swich==='map'" class="left">
        <!-- scroll-wheel-zoom：是否可以用鼠标滚轮控制地图缩放 -->
        <div class="name-box"><el-checkbox v-model="showName">显示名称</el-checkbox></div>
        <baidu-map
          ref="map"
          :key="updateMap"
          :map-click="false"
          style="height: 625px;"
          :enable-drawing-tool="true"
          scroll-wheel-zoom
          class="order_map"
          :center="center"
          :zoom="10"
          @ready="handler"
        >
          <template v-if="showName">
            <template v-if="fenceData.length">
              <!-- <bm-marker v-for="(item,index) in tableData" :key="index" :position="{lng: item.longitude, lat: item.latitude}" :icon="markerIcon" :dragging="false"> -->
              <bm-label v-for="item in fenceData" :key="item.id" :position="{lng: item.longitude, lat: item.latitude}" :title="item.fenceName" :content="item.fenceName" :label-style="{color: 'blue', fontSize : '14px', textAlign: 'center' , width: '80px', background: 'none' , border: 'none'}" :offset="{width:-20, height: -20}" />
              <!-- </bm-marker> -->
            </template>
            <template v-if="fenceData1.length">
              <!-- <bm-marker v-for="(item,index) in tableData1" :key="index" :position="{lng: item.longitude, lat: item.latitude}" :icon="markerIcon" :dragging="false"> -->
              <bm-label v-for="item in fenceData1" :key="item.id" :position="{lng: item.longitude, lat: item.latitude}" :title="item.fenceName" :content="item.fenceName" :label-style="{color: 'red', fontSize : '12px', textAlign: 'center' , width: '80px', background: 'none' , border: 'none'}" :offset="{width:-20, height: -20}" />
              <!-- </bm-marker> -->
            </template>
          </template>
        </baidu-map>
      </div>
      <lb-table
        ref=""
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        class="right"
        highlight-current-row
        element-loading-text="加载中"
        :column="orgidData.column"
        :data="orgidData.data"
        :total="orgidData.total"
        height="100%"
        style="margin-left: 10px; overflow: auto;"
        custom-column
      />
    </div>
    <orderDetailList ref="orderDetailList" :tree-data="treeData" :router-type="1" />
    <sendOrdersTacticsDetail ref="sendOrdersTacticsDetail" />
    <csm-detail
      ref="csmDetail"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
    />
    <warnInfo ref="warnInfo" />
  </div>
</template>

<script>
  import { parseTime, formatColumnMap, formatDate } from '@/utils'
  import moment from 'dayjs'
  import { mapGetters } from 'vuex'
  import { queryMap, queryTransactorList, queryDispatcherStat, dispatchDetail, batchUserOrder, queryOrgidInfo, queryBatchOrderList, batchOrderTransfer, queryCsmTypeMap, dispatchGet, dispatchSet, isTranGet, warnLevelList, selectUserFence } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import orderDetailList from '../../orderCenter/batchDispath/batchDispathList/orderDetail.vue'
  import sendOrdersTacticsDetail from '../../orderCenter/ordersTactics/sendOrdersTactics/sendOrdersTacticsDetail'
  import CsmDetail from '@/views/components/CsmDetailModal/index.vue'
  import OrderDetail from '@/views/orderCenter/orderManage/components/OrderDetails'
  import warnInfo from '@/views/customerCenter/customerManage/components/WarnInfo'
  var greenIcon = require('@/assets/map_images/green_sprite.png')
  var blueIcon = require('@/assets/map_images/blue_sprite.png')
  var redIcon = require('@/assets/map_images/red_sprite.png')
  var yellowIcon = require('@/assets/map_images/yellow_sprite.png')

  String.format = function(B) {
    var A = Array.prototype.slice.call(arguments, 1)
    return B.replace(/\{(\d+)\}/g, function(C, D) {
      return A[D]
    })
  }
  export default {
    name: 'batchDispathList',
    components: {
      orderDetailList,
      sendOrdersTacticsDetail,
      CsmDetail,
      OrderDetail,
      warnInfo
    },
    data() {
      return {
        showName: true,
        type: 'week',
        noReceiveList: [], // 待接单订单列表
        orderOfDispatcherList: [], // 调度员订单列表
        warnLevelList: [],
        overTimeTypeMap: [],
        tactics: null,
        statistics: null,
        swich: 'form',
        treeData: [],
        show: false,
        center: '',
        orderOne: 0,
        orderTwo: 0,
        orderThree: 0,
        orderFour: 0,
        csmTypeMapList: [],
        orderPointMarkers: [],
        updateMap: 0,
        ownersList: [],
        polygonPath: {
          editing: false,
          paths: [] // 绘制完成后的经纬度，其实是在画的时候动态push的，因为在点击的时候触发了 paintPolygon 函数
        },
        zoom: 3,
        map: null,
        fenceData: [],
        fenceData1: [],
        orderDispatchStausMap: [{ desc: '失败', value: 1 }, { desc: '成功', value: 2 }],
        query: {
          tranStatus: 1,
          userId: null,
          orgSNNo: '',
          orgId: null,
          date: [],
          date1: [],
          option: false,
          orderDispatchStaus: 1
        },
        seletctIdList: [],
        tableData1: [], // 地图派单数据
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              type: 'selection'
            },
            {
              prop: 'orderCode',
              label: '单号',
              align: 'center',
              width: 100,
              fixed: true,
              render: (h, { row }) => row.orderCode ? <el-link underline={false} onClick={() => this.openOrderDetail(row)}>{row.orderCode}</el-link> : <span>{row.orderCode}</span>
            },
            {
              prop: 'csmAddress',
              label: '地址',
              width: 300,
              showOverflowTooltip: true
            },
            {
              prop: 'goodsCount',
              label: '商品数量',
              align: 'right'
            },
            {
              prop: 'ownerName',
              label: '归属人'
            },
            {
              prop: 'goodsDesc',
              label: '商品描述',
              showOverflowTooltip: true,
              width: 200
            },
            {
              prop: 'orgName',
              label: '所属机构',
              width: 100,
              showOverflowTooltip: true
            },
            {
              prop: 'csmCode',
              label: '客户编号',
              width: 100,
              showOverflowTooltip: true,
              render: (h, { row }) => row.csmCode ? <el-link underline={false} onClick={() => this.openCsm(row)}>{row.csmCode}</el-link> : <span>{row.csmCode}</span>
            },
            {
              prop: 'csmName',
              label: '客户名称',
              width: 100
            },
            {
              prop: 'contactPhone',
              label: '客户电话',
              width: 110
            },
            {
              prop: 'transactTime',
              label: '下单时间',
              width: 180,
              render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'appointmentDt',
              label: '预约时间',
              width: 180,
              render: (h, { row }) => {
                return (
                  <div class={this.getClass(row)}>
                    {(row.appointmentDt && row.dateTimeSpare1) && <span>{parseTime(row.dateTimeSpare1, '{h}:{i}') === '23:59' ? parseTime(row.appointmentDt, '{y}-{m}-{d}') : parseTime(row.appointmentDt, '{y}-{m}-{d} {h}:{i}') + ' 至 ' + parseTime(row.dateTimeSpare1, '{h}:{i}')}</span>}
                  </div>
                )
              }
            },
            // {
            //   prop: 'appointmentDt',
            //   label: '配送时效区间',
            //   width: 180,
            //   render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            // },
            {
              prop: 'remark',
              label: '备注',
              width: 250,
              showOverflowTooltip: true
            },
            {
              prop: 'csmType',
              label: '客户类型',
              render: (h, { row }) => <span>{row.csmType ? formatColumnMap(this.csmTypeMapList, 'value', row.csmType, 'desc') : '' }</span>
            },
            {
              prop: 'warnLevel',
              label: '隐患等级',
              showOverflowTooltip: true,
              render: (h, { row }) =>
                row.warnLevel ? (
              <el-link underline={false} onClick={() => this.warnInfo(row)}>
                {formatColumnMap(this.warnLevelList, 'keyVal', row.warnLevel, 'keyName')}
              </el-link>
                  ) : (
              <span>无隐患</span>
            )
            },
            {
              prop: 'overTimeType',
              label: '超时状态',
              render: (h, { row }) => <span class={this.statusClass(row.overTimeType)}>{formatColumnMap(this.overTimeTypeMap, 'value', row.overTimeType, 'desc')}</span>
            },
            {
              prop: 'fromPlat',
              label: '来源',
              showOverflowTooltip: true,
              render: (h, { row }) => <span>{row.fromPlat ? formatColumnMap(this.orderSourceMap, 'value', row.fromPlat, 'desc') : '' }</span>
            },
            {
              prop: 'orderDispatchStaus',
              label: '派单状态',
              render: (h, { row }) => <span >{ row.orderDispatchStaus ? formatColumnMap(this.orderDispatchStausMap, 'value', row.orderDispatchStaus, 'desc') : ''}</span>
            }
          ],
          data: []
        },
        orgidData: {
          column: [
            {
              type: 'index',
              align: 'center'
            },
            {
              align: 'center',
              width: 80,
              render: (h, { row }) => <el-link v-show={row.onlineFlag} underline={false} onClick={() => this.allot(row)}>分派至</el-link>
            },
            {
              prop: 'userName',
              label: '配送员',
              width: 70,
              showOverflowTooltip: true
            },
            {
              label: '围栏名称',
              width: 80,
              showOverflowTooltip: true,
              render: (h, { row }) => <span>{row.fenceName && row.fenceName.length > 1 ? row.fenceName.join(',') : row.fenceName}</span>
            },
            {
              prop: 'orderCount',
              label: '待配送',
              align: 'left',
              width: 70,
              render: (h, { row }) => row.orderCount ? <el-link onClick={() => this.openOrderDetailList(row)}>{row.orderCount}</el-link> : <span>{row.orderCount}</span>
            },
            {
              prop: 'goodsCount',
              label: '商品数',
              width: 70,
              align: 'left'
            },
            {
              prop: 'bottleCount',
              label: '今日签收瓶数',
              width: 110,
              align: 'left'
            }
          ],
          data: []
        },
        muList: [],
        dispatchFlag: false,
        userNameOnline: [],
        defaultLabel: [],
        showSwitch: false,
        calcTypeList: [], // 收款方式枚举
        paymenFilList: [], // 付款方式枚举
        transactorList: [], // 处理人列表
        orderStatusMap: [],
        orderFlagMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        orderSourceMap: [],
        fromPlatList: [],
        mapParams: null,
        automaticPrint: JSON.parse(localStorage.getItem('automaticPrint')) || false
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'userInfo', 'corpSettingData'
      ]),
      goodsTotal() {
        return this.muList.reduce((item, current) => item + current.goodsCount, 0)
      }
    },
    watch: {
      'mapParams': {
        async handler(newVal, oldVal) {
          // console.log(newVal, oldVal)
          if (this.swich === 'map') {
            const res1 = await queryBatchOrderList({ ...this.mapParams, currentPage: 1, pageSize: 9999 })
            this.tableData1 = res1.data.rows
          }
        },
        deep: true,
        immediate: true
      }
    },
    async created() {
      await Promise.all([this.getTimeFn(), this.getTreeData(), this.queryOptionsMap(), this.getCsmType(), this.getInfo()])
      this.dispatchGet()
      this.isTranGet()
      this.getWarnLevelList()
      this.queryTime(this.type)
      const companyInfo = JSON.parse(sessionStorage.getItem('companyInfo'))
      // console.log('companyInfo', companyInfo)
      if (companyInfo) {
        this.center = companyInfo.city || '北京'
      }
    },
    mounted() {
      // 归属人默认为当前登录账号
      // this.query.userId = this.userInfo.userId
    },
    methods: {
      queryTime(type) {
        this.type = type
        if (type === 'three') {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
          this.query.date = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', parseTime(end, '{y}-{m}-{d}') + ' 23:59:59']
          this.search()
        }
        if (type === 'week') {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          this.query.date = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', parseTime(end, '{y}-{m}-{d}') + ' 23:59:59']
          this.search()
        }
        if (type === 'month') {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          this.query.date = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', parseTime(end, '{y}-{m}-{d}') + ' 23:59:59']
          this.search()
        }
      },
      getClass(r) {
        if (r.overTimeType) {
          if (r.overTimeType === 1) {
            return 'yellow'
          }
          if (r.overTimeType === 2) {
            return 'red'
          }
        }
      },
      getTimeFn() {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
        const start1 = new Date()
        const end1 = new Date()
        start1.setTime(start1.getTime() - 3600 * 1000 * 24 * 3)
        end1.setTime(end1.getTime() + 3600 * 1000 * 24 * 3)
        this.query.date[0] = formatDate(start, 'yyyy-MM-dd') + ' 00:00:00'
        this.query.date[1] = formatDate(end, 'yyyy-MM-dd') + ' 23:59:59'
        this.query.date1[0] = formatDate(start1, 'yyyy-MM-dd') + ' 00:00:00'
        this.query.date1[1] = formatDate(end1, 'yyyy-MM-dd') + ' 23:59:59'
      },
      parseTime,
      // 查询字典枚举
      async queryOptionsMap() {
        const [res4, res5, res6, res7, res8, res9] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' })
        ])
        this.calcTypeList = res4.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res5.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.orderStatusMap = res6.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res7.data // 订单类型
        this.payStatusMap = res8.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.orderSourceMap = res9.data // 订单来源
        this.getTransactorList()
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      // 订单详情
      async openOrderDetail(row) {
        await this.$refs.orderDetail.open(row, true)
      },
      // 打开客户
      async openCsm(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 点击订单号
      async openOrderDetailList(row) {
        await this.$refs.orderDetailList.open(row)
      },
      async fetchData({ currentPage, pageSize }) {
        const params = {
          currentPage,
          pageSize,
          orderStatus: 2,
          orgSNNo: this.query.orgSNNo,
          ownerIds: this.query.userId || [],
          tranStatus: this.query.tranStatus,
          orderDispatchStaus: this.query.orderDispatchStaus
        }
        if (this.query.date && this.query.date.length) {
          params['transactTime'] = parseTime(this.query.date[0], '{y}-{m}-{d} 00:00:00')
          params['transactTimeEnd'] = parseTime(this.query.date[1], '{y}-{m}-{d} 23:59:59')
          if (moment(this.query.date[1]).diff(moment(this.query.date[0]), 'days') > 31) {
            this.$message.error('选择时间条件相差不能超过1个月')
            return
          }
        } else {
          params['transactTime'] = ''
          params['transactTimeEnd'] = ''
        }
        if (this.query.date1 && this.query.date1.length) {
          params['appointmentDt'] = moment(this.query.date1[0]).format()
          params['dateTimeSpare1'] = moment(this.query.date1[1]).format()
          if (moment(this.query.date1[1]).diff(moment(this.query.date1[0]), 'days') > 31) {
            this.$message.error('选择时间条件相差不能超过1个月')
            return
          }
        } else {
          params['appointmentDt'] = ''
          params['dateTimeSpare1'] = ''
        }
        for (var value in params) {
          if (!params[value]) {
            delete params[value]
          }
        }
        params.orgId = this.query.option ? 0 : this.query.orgId
        this.mapParams = params
        const res = await queryBatchOrderList(params)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        await this.getUserOrder()
        await this.updateMap++
      },
      async getUserOrder() {
        const params = {
          orgSNNo: this.query.orgSNNo

        }
        const res = await batchUserOrder(params)
        this.orgidData.data = res.data
        this.userNameOnline = []
        this.defaultLabel = []
        this.orgidData.data.forEach((item) => {
          item.onlineFlag = 1
          this.userNameOnline.push(item.userId)
          this.defaultLabel.push(item.userName)
        })
        // console.log(this.userNameOnline)
      },
      async isTranGet() {
        const res = await isTranGet()
        this.showSwitch = res.data.isTran
      },
      addZoom() {
        // console.log(this.$refs.map)
      },
      infoWindowClose() {
        this.show = false
      },
      infoWindowOpen() {
        this.show = true
      },
      // 机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.query.orgSNNo = this.userInfo.orgSNNo
        this.query.orgId = this.userInfo.orgId
        // console.log('orgId', this.query.orgId)
        // console.log('orgSNNo', this.query.orgSNNo)
      },
      async getInfo() {
        await this.getOwnersList()
        const res1 = await dispatchDetail({ orgId: this.query.orgId })
        const res2 = await queryDispatcherStat({
          orderDispatchStaus: this.query.orderDispatchStaus,
          orgId: this.query.option ? 0 : this.query.orgId,
          orgSNNo: this.query.orgSNNo,
          tranStatus: this.query.tranStatus,
          transactTime: parseTime(this.query.date[0], '{y}-{m}-{d} 00:00:00'),
          transactTimeEnd: parseTime(this.query.date[1], '{y}-{m}-{d} 23:59:59'),
          ownerIds: this.query.userId })
        this.tactics = res1.data
        this.statistics = res2.data
      },
      // 选择所属机构
      async selectTreeChange(value) {
        this.query.userId = []
        this.query.orgId = value.orgId
        this.getOwnersList()
        await this.getUserOrder()
      },
      async dispatchGet() {
        const res = await dispatchGet()
        this.dispatchFlag = !!res.data.dispatchFlag
      },
      async dispatchFlagChange(value) {
        await dispatchSet({ dispatchFlag: value ? 1 : 0 })
      },
      // 清空所属机构
      closeTree(v) {
        this.$set(this.query, 'userId', [])
        this.ownersList = []
      },
      // 查询处理人列表
      async getOwnersList() {
        // const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOrgidInfo({
          orgSNNo: this.query.orgSNNo || this.userInfo.orgSNNo
        })
        this.ownersList = res.data
        this.ownersList.forEach(item => {
          if ((item.utype & 32768) > 0) {
            this.query.userId.push(item.userId)
          }
        })
      },
      // 地图点的点击事件
      clickMarker(l) {
        console.log(event.srcElement.style)
      },
      // 隐患详情
      warnInfo(row) {
        this.$refs.warnInfo.open(row)
      },
      // 勾选
      async selectCheck(data, node) {
        // console.log('data',data)
        // console.log('node',node.checkedKeys)
        // console.log(this.userNameOnline)
        // await this.orgidData.data.forEach((item) => {
        //  if (node.checkedKeys.indexOf(item.userId) === -1) {
        //     item.onlineFlag = 0
        //   }else{
        //     item.onlineFlag = 1
        //   }
        // })
        // const paramData = []
        // this.orgidData.data.forEach((item) => {
        //   if (node.checkedKeys.indexOf(item.userId) > -1) {
        //     const obj = {
        //       userId: item.userId,
        //       onlineFlag: 0
        //     }
        //     paramData.push(obj)
        //   } else {
        //     const obj = {
        //       userId: item.userId,
        //       onlineFlag: 1
        //     }
        //     paramData.push(obj)
        //   }
        // })
        // await userOnlineSet(paramData)
        // this.getUserOrder()
      },
      // 清除
      closeTag() {
        this.orgidData.data.forEach((item) => {
          item.onlineFlag = 0
        })
      },
      // 移出
      async inputChange(ids) {
        // console.log(ids)
        await this.orgidData.data.forEach((item) => {
          if (ids.indexOf(item.userId) === -1) {
            item.onlineFlag = 0
          } else {
            item.onlineFlag = 1
          }
        })
        // const paramData = []
        // this.orgidData.data.forEach((item) => {
        //   if (ids.indexOf(item.userId) > -1) {
        //     const obj = {
        //       userId: item.userId,
        //       onlineFlag: 0
        //     }
        //     paramData.push(obj)
        //   } else {
        //     const obj = {
        //       userId: item.userId,
        //       onlineFlag: 1
        //     }
        //     paramData.push(obj)
        //   }
        // })
        // await userOnlineSet(paramData)
        // this.getUserOrder()
      },
      // 打开策略详情
      async openTacticsDetail(row) {
        await this.$refs.sendOrdersTacticsDetail.open(row)
      },
      // 查询
      async search() {
        // console.log(this.query.orgId)
        this.$refs.lbTable.fetch({ currentPage: 1 })
        const res1 = await dispatchDetail({ orgId: this.query.orgId })
        const res2 = await queryDispatcherStat({
          orderDispatchStaus: this.query.orderDispatchStaus ? this.query.orderDispatchStaus : null,
          orgId: this.query.option ? 0 : this.query.orgId,
          orgSNNo: this.query.orgSNNo,
          tranStatus: this.query.tranStatus,
          transactTime: parseTime(this.query.date[0], '{y}-{m}-{d} 00:00:00'),
          transactTimeEnd: parseTime(this.query.date[1], '{y}-{m}-{d} 23:59:59'),
          ownerIds: this.query.userId })
        this.tactics = res1.data
        this.statistics = res2.data
        if (this.query.orgId && this.map) {
          setTimeout(() => {
            this.chooseOrg(this.query.orgId)
          }, 1000)
        }
      },
      async getCsmType() {
        const res = await queryCsmTypeMap()
        this.csmTypeMapList = res.data
        this.overTimeTypeMap = [{ desc: '正常', value: 0 }, { desc: '超时预警', value: 1 }, { desc: '已超时', value: 2 }]
        // console.log(this.csmTypeMapList)
        // console.log(this.overTimeTypeMap)
      },
      async getWarnLevelList() {
        const res = await warnLevelList()
        this.warnLevelList = res.data
      },
      // 点击选择
      handleSelectionChange(val) {
        this.muList = val
        console.log(val)
        this.seletctIdList = val.map(l => {
          return { orderCode: l.orderCode, ownerId: l.ownerId, ownerName: l.ownerName }
        })
      },
      // 分派
      allot(row) {
        if (this.swich === 'map') {
          var markerPoints = this.orderPointMarkers
          var list = []
          if (markerPoints.length > 0) {
            for (var x = 0; x < markerPoints.length; x++) {
              var imageUrl = markerPoints[x].getIcon().imageUrl
              if (imageUrl === blueIcon) {
                list.push(markerPoints[x])
              }
            }
          }
          const num = list.length
          if (!num) {
            this.$message.warning('请先选择订单')
            return false
          }
          this.$confirm(`是否将选中的${num}个订单分配给${row.userName}`).then(async() => {
            const orderBillInfoList = list.map(l => {
              return { ...row, ...l.submitParam }
            })
            const params = {
              json: { orderBillInfoList }
            }
            const res = await batchOrderTransfer(params)
            if (res.success) {
              this.$notify({
                title: '提示',
                message: `分派成功`,
                type: 'success',
                duration: 1000
              })
              if (this.automaticPrint) {
                await this.$refs.orderDetailList.printOrder(orderBillInfoList)
              }
              this.$refs.lbTable.fetch({ currentPage: 1 })
            }
          }).catch(e => {
            console.log(e)
          })
          return '地图模式分派'
        }
        // 表格模式分派
        const num = this.seletctIdList.length
        if (!num) {
          this.$message.warning('请先选择订单')
          return false
        }
        this.$confirm(`是否将选中的${num}个订单分配给${row.userName}`).then(async() => {
          const orderBillInfoList = this.seletctIdList.map(l => {
            return { ...row, ...l }
          })
          const params = {
            json: { orderBillInfoList }
          }
          const res = await batchOrderTransfer(params)
          if (res.success) {
            this.$notify({
              title: '提示',
              message: `分派成功`,
              type: 'success',
              duration: 1000
            })
            if (this.automaticPrint) {
              const list = JSON.parse(JSON.stringify(orderBillInfoList))
              await this.$refs.orderDetailList.printOrder(list)
            }
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
          console.log(orderBillInfoList)
        }).catch(e => {
          console.log(e)
        })
      },
      // 切换模式
      async cut() {
        if (this.swich === 'form') {
          const res1 = await queryBatchOrderList({ ...this.mapParams, currentPage: 1, pageSize: 9999 })
          this.tableData1 = res1.data.rows
          this.seletctIdList = []
          this.$refs.lbTable.clearSelection()
          this.swich = 'map'
        } else {
          this.swich = 'form'
          this.seletctIdList = []
        }
      },
      async handler({ BMap, map }) {
        this.map = map
        const vm = this
        // var poi = new BMap.Point(116.307852, 40.057031)
        // map.centerAndZoom(poi, 16)
        var overlays = []
        vm.orderPointMarkers = [] // 初始化点

        var data = vm.tableData1
        if (data.length > 0) {
          for (var x = 0; x < data.length; x++) {
            if (!(data[x].lon * 1) || !(data[x].lat * 1)) {
              continue
            }
            // 设置覆盖物图标
            var icon = new BMap.Icon(redIcon, new BMap.Size(19, 25))
            if (data[x].orderQueryType === 1) {
              icon.imageUrl = redIcon
            }
            if (data[x].orderQueryType === 2) {
              icon.imageUrl = yellowIcon
            }
            if (data[x].orderQueryType === 3) {
              icon.imageUrl = greenIcon
            }
            // 是否选中
            icon.bean = data[x]
            icon.bean.isChecked = false
            var pt = new BMap.Point(data[x].lon, data[x].lat)
            var marker = new BMap.Marker(pt, { icon: icon })
            // 表示障碍物 没有点击
            // icon.imageUrl = "/image/map/marker_red_sprite.png";
            var template = "<span style='margin-right: 20px;height: 28px;display:inline-block;width: 200px;'>订&ensp;单&ensp;号： {0}</span><span style='height: 28px;display:inline-block;'> 客户编号： {1}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;width: 200px;'>联&ensp;系&ensp;人： {2}</span><span style='height: 28px;display:inline-block;'>联系电话： {3}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>地&ensp;&ensp;&ensp;&ensp;址： {4}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>商品描述： {5}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>下单时间： {6}</span><br/>"
            marker.orderCode = data[x].orderCode || ''
            marker.csmCode = data[x].csmCode || ''
            marker.contact = data[x].contact || ''
            marker.contactPhone = data[x].contactPhone || ''
            marker.csmAddress = data[x].csmAddress || ''
            marker.goodsDesc = data[x].goodsDesc || ''
            marker.transactTime = vm.parseTime(data[x].transactTime, '{y}-{m}-{d} {h}:{i}:{s}') || ''
            marker.submitParam = { orderCode: data[x].orderCode, ownerId: data[x].ownerId, ownerName: data[x].ownerName }

            marker.addEventListener('mouseover', function() {
              var content = String.format(template, this.orderCode, this.csmCode, this.contact, this.contactPhone, this.csmAddress, this.goodsDesc, this.transactTime)
              var tempInfoWindow = new BMap.InfoWindow(content, {
                width: 400, // 信息窗口宽度
                height: 200, // 信息窗口高度
                title: '', // 信息窗口标题
                enableMessage: true// 设置允许信息窗发送短息
              })
              this.openInfoWindow(tempInfoWindow)
            })
            marker.addEventListener('mouseout', function() {
              this.closeInfoWindow()
            })

            marker.addEventListener('click', function(e) {
              var icon = this.getIcon()
              if (icon.bean.isChecked) {
                if (icon.bean.orderQueryType === 2) {
                  icon.imageUrl = yellowIcon
                } else if (icon.bean.orderQueryType === 3) {
                  icon.imageUrl = greenIcon
                } else {
                  icon.imageUrl = redIcon
                }
                icon.bean.isChecked = false
                this.setIcon(icon)
              } else {
                icon.imageUrl = blueIcon
                // 是否选中
                icon.bean.isChecked = true
                this.setIcon(icon)
              }
              // 更新数量
              vm.orderNumCount()
            })
            // vm.orderNumCount()
            // marker.setAnimation(BMAP_ANIMATION_BOUNCE) // 跳动的动画
            // 增加点
            map.addOverlay(marker) // 将标注添加到地图中
            // 存储所有marker
            vm.orderPointMarkers.push(marker)
          }
          // console.log(vm.orderPointMarkers)
        }
        // 更新数量
        vm.orderNumCount()

        // eslint-disable-next-line no-unused-vars
        var overlaycomplete = function(e) {
          overlays.push(e.overlay)
          switch (e.drawingMode) {
          // 图像标注
          case 'marker':break
          // 线的样式
          case 'polyline':

            break
          // 圆
          case 'circle':
            break
          // 多边形
          case 'polygon':
            break
          // 矩形
          case 'rectangle':
            var data = vm.tableData.data
            if (data.length > 0) {
              for (var x = 0; x < data.length; x++) {
                if (data[x].lon === undefined || data[x].lat === undefined) {
                  continue
                }
                var pt = new BMap.Point(data[x].lon, data[x].lat)
                // 矩形  或  多边形
                if (window.BMapLib.GeoUtils.isPointInPolygon(pt, e.overlay)) {
                  var markers = vm.orderPointMarkers
                  if (markers.length > 0) {
                    for (var a = 0; a < markers.length; a++) {
                      var markerIcon = markers[a].getIcon()
                      if (markerIcon.bean !== undefined) {
                        if (markerIcon.bean.orderCode === data[x].orderCode) {
                          markerIcon.imageUrl = blueIcon
                          // 是否选中
                          markerIcon.bean.isChecked = true
                          markers[a].setIcon(markerIcon)
                        }
                      }
                    }
                  }
                }
              }
            }
            break
          }
          // 地图上移除覆盖物
          // eslint-disable-next-line no-undef
          clearAll()
          // 更新数量
          vm.orderNumCount()
          // console.log(overlays[0].Wu.getNorthEast())
        }
        // var styleOptions = {
        //   strokeColor: 'red', // 边线颜色。
        //   fillColor: 'red', // 填充颜色。当参数为空时，圆形将没有填充效果。
        //   strokeWeight: 3, // 边线的宽度，以像素为单位。
        //   strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
        //   fillOpacity: 0.6, // 填充的透明度，取值范围0 - 1。
        //   strokeStyle: 'solid' // 边线的样式，solid或dashed。
        // }
        // 实例化鼠标绘制工具
        // var drawingManager = new window.BMapLib.DrawingManager(map, {
        //   isOpen: false, // 是否开启绘制模式
        //   enableDrawingTool: true, // 是否显示工具栏
        //   drawingToolOptions: {
        //     anchor: window.BMAP_ANCHOR_TOP_RIGHT, // 位置
        //     offset: new BMap.Size(5, 5) // 偏离值
        //   },
        //   circleOptions: styleOptions, // 圆的样式
        //   polylineOptions: styleOptions, // 线的样式
        //   polygonOptions: styleOptions, // 多边形的样式
        //   rectangleOptions: styleOptions // 矩形的样式
        // })
        // document.querySelectorAll('.order_map .BMapLib_marker')[0].style.display = 'none'
        // document.querySelectorAll('.order_map .BMapLib_circle')[0].style.display = 'none'
        // document.querySelectorAll('.order_map .BMapLib_polyline')[0].style.display = 'none'
        // document.querySelectorAll('.order_map .BMapLib_polygon')[0].style.display = 'none'
        // 添加鼠标绘制工具监听事件，用于获取绘制结果
        // drawingManager.addEventListener('overlaycomplete', overlaycomplete)
        // function clearAll() {
        //   for (var i = 0; i < overlays.length; i++) {
        //     map.removeOverlay(overlays[i])
        //   }
        //   overlays.length = 0
        // }
        // map.enableScrollWheelZoom(true)
        // map.centerAndZoom('青岛市', 13)
      },
      orderNumCount() {
        const vm = this
        var orderOne = 0
        var orderTwo = 0
        var orderThree = 0
        var orderFour = 0
        var markerPoints = vm.orderPointMarkers
        if (markerPoints.length > 0) {
          for (var x = 0; x < markerPoints.length; x++) {
            var imageUrl = markerPoints[x].getIcon().imageUrl
            // 红色
            if (imageUrl === redIcon) {
              orderOne = orderOne + 1
              // 蓝色
            } else if (imageUrl === blueIcon) {
              orderTwo = orderTwo + 1
              // 黄色
            } else if (imageUrl === yellowIcon) {
              orderThree = orderThree + 1
              // 绿色
            } else if (imageUrl === greenIcon) {
              orderFour = orderFour + 1
            }
          }
        }
        this.orderOne = orderOne
        this.orderTwo = orderTwo
        this.orderThree = orderThree
        this.orderFour = orderFour
        // console.log(orderOne, orderTwo, orderThree)
      },
      // 选中站点
      async chooseOrg(value) {
        this.chooseOrgId = value
        // 查询站点围栏和下面的子围栏
        await selectUserFence({ orgId: value }).then(res => {
          if (res.data) {
            this.fenceData = []
            this.fenceData1 = []
            this.fenceData = res.data.filter(item => {
              if (item.fenceType === 1) {
                item.showDetail = false
                item.path = JSON.parse(item.coordinates)
                const options = {
                  strokeColor: item.borderColor, // 边线颜色。
                  fillColor: item.fillColor, // 填充颜色。当参数为空时，圆形将没有填充效果。
                  strokeWeight: 5, // 边线的宽度，以像素为单位。
                  strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
                  fillOpacity: item.fillOpacity || 0.6, // 填充的透明度，取值范围0 - 1。
                  strokeStyle: 'dashed' // 边线的样式，solid或dashed。
                }
                const ps = []
                for (var i in item.path) {
                  // eslint-disable-next-line no-undef
                  ps.push(new BMap.Point(item.path[i].lng, item.path[i].lat))
                }
                // eslint-disable-next-line no-undef
                const polygon = new BMap.Polygon(ps, options) // 创建多边形
                item.polygon = polygon
                this.map.addOverlay(polygon)
                // eslint-disable-next-line no-undef
                this.map.centerAndZoom(new BMap.Point(item.lon, item.lat), 15)
                item.position = { lng: item.lon, lat: item.lat }
                return item
              }
            })
            this.fenceData1 = res.data.filter(item => {
              if (item.fenceType === 2) {
                item.path = JSON.parse(item.coordinates)
                const options = {
                  strokeColor: item.borderColor, // 边线颜色。
                  fillColor: item.fillColor, // 填充颜色。当参数为空时，圆形将没有填充效果。
                  strokeWeight: 5, // 边线的宽度，以像素为单位。
                  strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
                  fillOpacity: item.fillOpacity || 0.6, // 填充的透明度，取值范围0 - 1。
                  strokeStyle: 'dashed' // 边线的样式，solid或dashed。
                }
                const ps = []
                for (var i in item.path) {
                  // eslint-disable-next-line no-undef
                  ps.push(new BMap.Point(item.path[i].lng, item.path[i].lat))
                }
                // eslint-disable-next-line no-undef
                const polygon = new BMap.Polygon(ps, options) // 创建多边形
                item.polygon = polygon
                item.isOpen = item.isOpen === 1
                this.map.addOverlay(polygon)
                // eslint-disable-next-line no-undef
                this.map.centerAndZoom(new BMap.Point(item.lon, item.lat), 15)
                item.position = { lng: item.lon, lat: item.lat }
                return item
              }
            })
          // console.log(this.fenceData)
          // console.log(this.fenceData1)
          }
        }).catch(err => {
          console.log(err)
          this.fenceData = []
          this.fenceData1 = []
        })
      },
      statusClass(keyStatus) {
        if (keyStatus === 2) return 'red'
        else if (keyStatus === 1) return 'yellow'
        else return ''
      },
      chooseAutomaticPrint(val) {
        localStorage.setItem('automaticPrint', val)
      }
    }

  }

</script>

<style lang='scss' scoped>
.app-page {
  padding: 0 10px;
  overflow-y: hidden;
}
.table_Main {
  position: relative;
  display: flex;
  .left {
    position: relative;
    width: 100%;
    .name-box {
      position: absolute;
      top: 20px;
      left: 20px;
      z-index: 1200;
    }
  }
  .right {
    width: 45%;
  }
  .total {
    position: absolute;
    right: 35vw;
    bottom: 5px;
    font-size: 18px;
    font-weight: 800;
    color: #F00;
  }
}
.bm-view {
  width: 100%;
  height: 500px;
}
.infoWindow {
  width: 350px;
  height: 150px;
  padding: 5px;
  font-size: 14px;
  div {
    margin-top: 10px;
  }
}
.tactics {
  display: flex;
  div {
    margin-right: 20px;
  }
}
.handle-row {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
}
.btnInfo {
  display: flex;
  font-size: 14px;
  // height:20px;
  img {
    width: 15px;
    height: 20px;
  }
  span {
    margin-right: 8px;
    line-height: 20px;
    text-align: center;
  }
  .btn {
    flex: 1;
  }
}
.statistics {
  div {
    margin-right: 20px;
    font-size: 14px;
  }
}
.switch-item {
  position: relative;
  top: 5px;
  margin: 0 10px;
}
/deep/.red {
  color: #f00 !important;
}
/deep/.yellow {
  color: #ed912e !important;
}

/* 隐藏百度图片Logo */
/deep/ .BMap_cpyCtrl {
  display: none;
}
/deep/ .anchorBL {
  display: none;
}
</style>
